<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper" style="overflow: hidden" ref="myElement">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -19px">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="profile" style="margin-right: 8px; color:rgb(13, 158, 243)"></a-icon>基本信息
                  </a-divider>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查人员" required :labelCol="{ style: 'width:115px' }">
                  <a-input read-only :value="this.userInfo.nickName"></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查时间" required :labelCol="{ style: 'width:115px' }">
                  <date-picker
                    placeholder="选择日期"
                    :defaultValue="moment().subtract(1, 'second')"
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :showToday="true"
                    @change="onChangeTime"
                    v-model="checkTime"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-item label="检查类型" required :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.checkType" read-only></a-input>
                </a-form-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-item label="录入时间" required :labelCol="{ style: 'width:115px' }">
                  <a-input
                    read-only
                    v-model="enterTime"
                    format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-item label="数据来源" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择数据来源" v-model="submitInfo.enterSys" :rules="[{ required: true, message: '请选择数据来源'}]">
                    <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty" @click="chooseWorkSpecialty(item)">{{ item.specialty }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-item label="隐患单位" :loading="treeLoading" required :labelCol="{ style: 'width:115px' }">
                  <a-cascader
                    :style="{ width: selectWidth + 'px' }"
                    ref="orgTree"
                    tree-node-filter-prop="title"
                    :tree-check-strictly="true"
                    :show-search="true"
                    :show-all-levels="false"
                    style="width: 100%"
                    :dropdownStyle="{ maxHeight: 600, overflow: 'auto'}"
                    placeholder="请选择隐患单位"
                    allow-clear
                    :options="unitTree"
                    @change="handleOrganNameClick"
                    treeCheckStrictly
                    :rules="[{ required: true, message: '请选择隐患单位'}]"
                    :title="submitInfo.organizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业专业" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择作业专业" v-model="submitInfo.workSpecialty" style="font-weight: bold;">
                    <a-select-option
                      v-for="(item) in workSpecialData"
                      :key="item.id"
                      :value="item.specialty"
                      @click="chooseWorkSpecialty(item)">{{ item.specialty
                      }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业项目" required :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.workItem" allow-clear placeholder="请输入作业项目" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -20px">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="info-circle" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 关键作业信息
                  </a-divider>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="关键作业类型" :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择关键作业类型" v-model="submitInfo.workType">
                    <a-select-option v-for="(item) in workTypeData" :key="item.id" :value="item.workType" @click="chooseWorkType(item)">{{ item.workType }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="关键作业内容" :labelCol="{ style: 'width:115px' }">
                  <a-select
                    allow-clear
                    placeholder="请选择关键作业内容"
                    :show-search="true"
                    v-model="submitInfo.workContent"
                    :style="{ width: selectWidth + 'px' }"
                    :title="submitInfo.workContent">
                    <a-select-option v-for="(item) in workContentData" :key="item.id" :value="item.workContent" @click="chooseWorkContent(item)">{{ item.workContent }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="作业风险等级" :labelCol="{ style: 'width:115px' }">
                  <a-input v-model="submitInfo.workRisk"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item style="margin-bottom: 20px; margin-top: -20px">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="alert" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 隐患信息
                  </a-divider>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="16">
                <a-form-item label="隐患条款" required :labelCol="{ style: 'width:115px' }">
                  <a-select
                    v-model="submitInfo.dangerClause"
                    :style="{ width: selectWidth2 + 'px' }"
                    placeholder="请输入关键字段选择隐患条款"
                    show-search
                    allow-clear>
                    <a-select-option value="无对应条款" @click="noClause()"><b>无对应条款</b></a-select-option>
                    <a-select-option v-for="(item) in dangerClauseData" :key="item.generalSpecialtyId" :value="item.description" @click="chooseDangerClause(item)">{{ item.description }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item required label="隐患分类" style="margin-left: 25px;">
                  <a-radio-group v-model="submitInfo.dangerTypeCategory" @change="changeRadio" style="margin-left: 10px;">
                    <a-radio value="通用隐患" style="margin-left: 10px">通用隐患</a-radio>
                    <a-radio value="专业隐患" style="margin-left: 10px">专业隐患</a-radio>
                    <a-radio value="其他" style="margin-left: 10px">其他</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="隐患级别" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择隐患级别" v-model="submitInfo.dangerType">
                    <a-select-option v-for="(item) in dangerRiskData" :key="item.id" :value="item.item" @click="chooseDangerType(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="检查方式" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择检查方式" v-model="submitInfo.InspectionMethod">
                    <a-select-option v-for="item in dangerCheckData" :key="item.id" :value="item.item">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="位置区域" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择位置区域" :show-search="true" v-model="submitInfo.location">
                    <a-select-option v-for="(item) in locationData" :key="item.id" :value="item.location">{{ item.location }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="16">
                <a-form-item label="隐患描述" class="upload-item" required :labelCol="{ style: 'width:115px' }">
                  <a-textarea
                    v-model="submitInfo.description"
                    :title="submitInfo.description"
                    :rows="2"
                    :span="40"
                    allow-clear
                    placeholder="请输入隐患描述"/>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="归属部门" :labelCol="{ style: 'width:115px' }" required>
                  <a-select allow-clear placeholder="请选择归属部门" v-model="submitInfo.directDepartment">
                    <a-select-option v-for="(item) in departmentData" :key="item.id" :value="item.item" @click="choosedepart(item)" >{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="隐患类别" required :labelCol="{ style: 'width:115px' }">
                  <a-tree-select
                    :style="{ width: selectWidth + 'px' }"
                    v-model="submitInfo.dangerCategory"
                    treeNodeFilterProp="title"
                    :show-search="true"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: 400, overflow: 'auto' }"
                    placeholder="请选择隐患类别"
                    :allow-clear="true"
                    :tree-default-expand-all="false"
                    :tree-data="dangerTypeTree"
                    @change="handleDanCategoryClick"
                    :title="submitInfo.dangerCategory"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="对应要素体系" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="对应要素体系" v-model="submitInfo.hseElement">
                    <a-select-option v-for="(item) in hseData" :key="item.id" :value="item.item" @click="choosehse(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="原因分析" required :labelCol="{ style: 'width:115px' }">
                  <a-select allow-clear placeholder="请选择原因分析" v-model="submitInfo.causeAnalysis">
                    <a-select-option v-for="(item) in analysisData" :key="item.id" :value="item.item" @click="chooseanaly(item)">{{ item.item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12" class="upload-item">
                <a-form-item label="隐患图片" :labelCol="{ style: 'width:115px' }">
                  <!-- <a-progress
                    v-if="batchExportLoading"
                    :percent="progressPercentage"
                    status="active"
                  /> -->
                  <a-upload
                    name="dangerFile"
                    list-type="picture-card"
                    :file-list="fileList"
                    :showUploadList="true"
                    data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                    ref="DangerPics"
                    :before-upload="beforeUpload"
                    @change="handlePicChange"
                    :remove="handleRemove"
                    @preview="handlePreview"
                    :customRequest="customRequest"
                    multiple
                  >
                    <div v-if="dangerShowLoader" class="spinner"></div>
                    <div id="container" v-if="fileList.length < 4 && !dangerShowLoader">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                  </a-modal>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24" class="item3">
                <a-form-item style="margin-bottom: 20px;">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="tool" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 整改信息
                  </a-divider>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="整改负责人" required :labelCol="{ style: 'width:115px' }">
                  <a-input
                    suffix-icon="down"
                    v-model="submitInfo.reformerUserName"
                    @click="showModals"
                    allow-clear
                    read-only
                    ref="input"
                    placeholder="请选择整改负责人姓名"/>
                  <a-modal
                    @cancel="handleCancel"
                    :visible="visible"
                    :width="1400"
                    :height="2000"
                  >
                    <choose-people
                      :people-list="peopleList"
                      @cancel="handleCancel"
                      @chooseUser="chooseDangerPeople"
                      :userId="submitInfo.reformerUserId"
                    />
                    <template #footer>
                      <a-button type="default" @click="handleCancel">取消</a-button>
                    </template>
                  </a-modal>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="限期整改时间" required :labelCol="{ style: 'width:115px' }">
                  <date-picker
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :showToday="true"
                    v-model="reformTime"
                    placeholder="选择日期"
                    @change="onChangeTime2"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12" class="upload-item">
                <a-form-item label="整改图片" :labelCol="{ style: 'width:115px' }">
                  <!-- <a-progress
                    v-if="batchExportLoading2"
                    :percent="progressPercentage2"
                    status="active"
                  /> -->
                  <a-upload
                    name="reformerFile"
                    list-type="picture-card"
                    :file-list="fileList2"
                    :showUploadList="true"
                    data-type="jpg|png|jpeg|JPG|PNG|JPEG"
                    ref="ReformerPics"
                    :before-upload="beforeUpload2"
                    @change="handlePicChange2"
                    :remove="handleRemove2"
                    @preview="handlePreview2"
                    :customRequest="customRequest"
                    multiple
                  >
                    <div v-if="reformerShowLoader" class="spinner"></div>
                    <div id="container" v-if="fileList2.length < 4 && !reformerShowLoader">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible2" :footer="null" @cancel="handlePicCancel2">
                    <img alt="example" style="width: 100%" :src="previewImage2" />
                  </a-modal>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item style="margin-top: 20px; margin-bottom: 10px;">
                  <a-divider orientation="left" style="font-weight: bold">
                    <a-icon type="check-circle" style="margin-right: 8px;color:rgb(13, 158, 243)"></a-icon> 验收信息
                  </a-divider>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-item required>
                  <a-radio-group v-model="submitInfo.status" @change="handleRadioChange" style="margin-left: 30px; margin-top: -60px">
                    <a-radio value="已整改" style="margin-left: 50px; margin-top: -30px">验收</a-radio>
                    <a-radio value="未整改" style="margin-left: 170px; margin-top: -30px">不验收</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item label="验收时间" :labelCol="{ style: 'width:115px' }">
                  <date-picker
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :showToday="true"
                    v-model="acceptTime"
                    placeholder="选择日期"
                    :disabled="submitInfo.status === '未整改'"
                    @change="onChangeTime3"
                    style="width: 100%"/>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-form-item label="验收描述" :labelCol="{ style: 'width:115px' }">
                  <a-textarea
                    v-model="submitInfo.checkDescription"
                    :disabled="submitInfo.status === '未整改'"
                    :rows="1"
                    :maxLength="200"
                    :span="40"
                    allow-clear
                    placeholder="请输入验收描述"/>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item style="text-align: center">
                  <a-button @click="saveList" type="primary" v-if="hasPerm('hdv_qhse_d_all_insert')" :loading="saving">保存</a-button>
                  <a-button @click="onSubmit2" v-show="hasPerm('hidden_danger_send')" :loading="saving1">保存并推送数据</a-button>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item style="text-align: center">
                  <a-button @click="onSubmit" type="primary" :disabled="!saved">新增下一条</a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
    </a-col>
  </a-row>
</template>
<script>
  import { Empty, DatePicker, TreeSelect, Select, Input, Upload, Form, Radio, Alert, Cascader } from 'ant-design-vue'
  import { STable, XCard, XDown, ChoosePeople } from '@/components'
  import Exif from 'exif-js'
  // import { danComparePic } from '@/api/modular/system/QHSEDanger'
  import {
    getUnitTree,
    getVioTypeTree,
    getYHAnalysisList,
    getDepartmentList,
    getWorkSpecialtyList,
    getKeyWorkTypeList,
    getKeyWorkContentList,
    getLocationList
  } from '@/api/modular/system/violationManage'
  import {
    addDangerInfo,
    getDangerCategoryHse,
    getHazardLevelList,
    getDangerTree,
    getDangerCheckType,
    editDangerInfo,
    getDangerClause,
    getDangerClauseAssocition
  } from '@/api/modular/system/QHSEDangerinsertManager'
  import moment from 'moment'
  import TagSelectOption from '@/components/TagSelect/TagSelectOption'
  import { mapGetters } from 'vuex'
  function getBase64 (file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = error => reject(error)
    })
  }
  async function readFileAsync(file) {
    const reader = new FileReader()
    if (file.originFileObj !== undefined) {
      reader.readAsDataURL(file.originFileObj)
      return new Promise((resolve, reject) => {
        reader.onload = function () {
          const base64String = reader.result.split(',')[1]
          resolve({ name: file.name, base64Content: base64String })
        }
        reader.onerror = function () {
          reject(new Error('读取失败'))
        }
      })
    } else {
      const parts = file.url.split(',')
      const base64String = parts[1]
      return { name: file.name, base64Content: base64String }
    }
  }
  async function convertFilesToArrayAsync(files) {
    const outputArray = []
    for (const file of files) {
      const output = await readFileAsync(file)
      // 在这里对输出对象进行进一步处理或者使用
      // console.log('output----', output)
      outputArray.push(output)
    }
    return outputArray
  }
  // 异步加载图片
  function loadImageAsync(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        const image = new Image()
        image.onload = () => resolve(image)
        image.onerror = reject
        image.src = e.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })
  }
  export default {
    components: {
      TagSelectOption,
      XDown,
      XCard,
      STable,
      DatePicker,
      TreeSelect,
      Select,
      Input,
      ChoosePeople,
      Upload,
      Form,
      Radio,
      Alert,
      'a-cascader': Cascader
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        labelCol_A: {
          xs: { span: 12 },
          sm: { span: 3 }
        },
        wrapperCol_A: {
          xs: { span: 36 },
          sm: { span: 20 }
        },
        labelCol_S: {
          xs: { span: 12 },
          sm: { span: 6 }
        },
        wrapperCol_S: {
          xs: { span: 20 },
          sm: { span: 13 }
        },
        searchWCode: {
          Code: ''
        },
        searchSCode: {
          Code: ''
        },
        searchCCode: {
          id: ''
        },
        secondOraName: {
          id: ''
        },
        searchSClauseCode: {
          SpecialtyCode: '',
          DangerTypeCode: ''
        },
        searchGClauseCode: {
          DangerTypeCode: ''
        },
        flag: true,
        previewImage: '',
        previewVisible: false,
        previewImage2: '',
        previewVisible2: false,
        ModalVisible: false,
        file: {
          name: '',
          base64Content: ''
        },
        file2: {
          name: '',
          base64Content: ''
        },
        addOrEdit: 0,
        fileList: [],
        fileList2: [],
        queryGeneralClause: {},
        queryEleCom: {},
        queryClause: {},
        danQueryGeneralClause: {},
        danQueryEleCom: {},
        danQueryClause: {},
        showCheckInfo: false,
        chooseDanTypeCode: '', // 选择的隐患类别code
        chooseWorkTypeCode: '', // 选择的关键作业类型code
        chooseSpecialtyCode: '', // 选择的作业专业code
        chooseWorkClauseCode: '',
        geneOrMajor: '', // 选择的违章类型按钮
        selectedKeys: [],
        nickName: '',
        disabledIds: [], // 存储disabled节点的id
        selectedIds: [], // 存储已选节点的id
        user: {},
        selectedName: null,
        form: this.$form.createForm(this),
        uploadingList: [],
        peopleList: [],
        // 选择的人员
        selectedPerson: {},
        showCheck: false,
        visible: false,
        // dialogVisible: false, // 是否显示选择人员界面
        submitInfo: {
          checkOrganizationId: '',
          qhseXyDangerId: '', // 违章id
          checkType: '', // 检查类型
          checkTypeCode: '',
          userId: '', // 检查人员id
          checkName: '', // 检查人员姓名
          checkDate: '', // 检查时间
          enterTime: '', // 录入时间
          enterSys: '公司隐患违章系统', // 数据来源
          organizationId: '', // 隐患单位id
          organizationName: '', // 隐患单位名
          workItem: '', // 作业项目
          workSpecialty: '钻井专业', // 作业专业
          workSpecialtyCode: 'SP1001', // 作业专业
          workType: '', // 关键作业类型
          keyWorkCode: '', // 关键作业类型
          workContent: '', // 关键作业内容
          workRisk: '', // 作业风险等级
          dangerType: '', // 隐患级别
          dangerTypeCode: '',
          description: '', // 隐患描述
          dangerCategory: '', // 隐患类别
          dangerCateId: '', // 隐患类别ID
          hseElement: '', // 对应要素体系
          hseCode: '', // 对应要素体系
          observeComm: '', // 对应安全沟通
          causeAnalysis: '', // 原因分析
          clauseAnalysisCode: '',
          directDepartment: '', // 归属部门
          departmentCode: '', // 归属部门
          potentialConsequence: '', // 可能后果
          location: '', // 位置区域
          dangerPic: '', // 隐患图片
          reformerUserId: '', // 整改负责人id
          reformerUserName: '', // 整改负责人姓名
          reformerDate: '', // 整改期限
          reformerPic: '', // 整改图片
          status: '未整改', //
          acceptanceDate: '', // 验收时间
          checkDescription: '', // 验收描述
          checkOrganizationName: '', // 验收部门
          dangerFiles: [], // 隐患图片
          reformerFiles: [], // 整改文件
          dangerTypeCategory: '', // 隐患性质分类
          dangerClause: undefined // 隐患条款
        },
        replaceFields: {
          key: 'id'
        },
        isCheckDescriptionDisabled: false,
        treeLoading: true,
        saved: false,
        chooseDanCategoryId: '', // 隐患类别ID
        workTypeData: [], // 关键作业类型
        workContentData: [], // 关键作业内容
        workRiskData: [], // 作业风险等级
        workSpecialData: [], // 作业专业
        userAgeData: [], // 年龄
        workAgeData: [], // 工龄
        employData: [], // 用工性质
        unitTree: [], // 违章单位
        positionData: [], // 违章岗位
        processData: [], // 作业工序
        locationData: [], // 位置区域
        elementData: [], // 对应要素体系
        danElementData: [], // 隐患对应要素体系
        vioNatureData: [], // 违章性质
        vioClauseData: [], // 违章条款
        communicateData: [], // 对应安全沟通
        vioTypeTree: [], // 违章类别
        dangerTypeTree: [], // 隐患类别
        analysisData: [], // 原因分析
        departmentData: [], // 归属部门
        resultData: [], // 可能后果
        dangerRiskData: [], // 隐患级别
        dangerCheckData: [], // 检查方式
        dangerClauseData: [], // 隐患条款
        hseData: [],
        saving: false,
        saving1: false,
        name: 'about',
        // 由于日期控件上绑定的是一个moment对象，所以初始化值要绑定一个undefined/而不是一个空字符串
        myDate: undefined,
        // 查询参数
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: (_parameter) => {

        },
        sexDictTypeDropDown: [],
        statusDictTypeDropDown: [],
        simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
        dangerShowLoader: false,
        reformerShowLoader: false,
        checkTime: null,
        enterTime: null,
        reformTime: null,
        acceptTime: null,
        selectWidth: 200,
        selectWidth2: 200
        // danComparePicFinished: false,
        // danComparePicFinished2: false,
        // progressPercentage: 90,
        // progressPercentage2: 90,
        // batchExportLoading: false,
        // batchExportLoading2: false
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    props: {
      dataProp: {
        type: Object,
        default: () => ({})
      }
    },
    async created() {
      try {
        // const date = new Date() // 获取当前日期
        // const year = date.getFullYear() // 获取年份
        // const month = ('0' + (date.getMonth() + 1)).slice(-2) // 获取月份，需要补 0
        // const day = ('0' + date.getDate()).slice(-2) // 获取日期，需要补 0
        // this.submitInfo.checkDate = `${year}-${month}-${day}` // 将日期赋值为年-月-日格式
        // this.submitInfo.reformerDate = `${year}-${month}-${day}`
        // this.submitInfo.acceptanceDate = `${year}-${month}-${day}`
        this.enterTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        const tmpTime = moment(this.enterTime).subtract(1, 'second').format('YYYY-MM-DD HH:mm:ss')
        this.submitInfo.enterTime = this.enterTime.replace(' ', 'T')
        this.submitInfo.checkDate = tmpTime.replace(' ', 'T')
        this.submitInfo.checkName = this.userInfo.nickName
        this.submitInfo.userId = this.userInfo.id
        this.submitInfo.checkOrganizationId = this.userInfo.currentOrganizationId
        this.submitInfo.secondOrganizationId = this.userInfo.secondOrganizationId
        this.submitInfo.thirdOrganizationId = this.userInfo.thirdOrganizationId
        this.submitInfo.dangerCategory = this.dangerCategory
        this.secondOraName.id = this.userInfo.secondOrganizationName
        // 获取作业专业列表
        getWorkSpecialtyList(Object.assign(this.queryParam)).then(res => {
          this.workSpecialData = res.data
        })
        // 获取作业专业为钻井专业的关键作业类型列表
        getKeyWorkTypeList({ 'Code': 'SP1001' }).then(res => {
          this.workTypeData = res.data.rows
        })
        // 获取作业专业为钻井专业的位置区域
        getLocationList({ 'Code': 'SP1001' }).then(res => {
          this.locationData = res.data.rows
        })
        // 获取原因分析列表
        getYHAnalysisList(Object.assign(this.queryParam)).then(res => {
          this.analysisData = res.data
        })
        // 获取归属部门列表
        getDepartmentList(Object.assign(this.queryParam)).then(res => {
          this.departmentData = res.data
        })

        // 获取隐患单位树
        getUnitTree(Object.assign(this.secondOraName)).then(res => {
          this.treeLoading = false
          this.unitTree = this.transformData(res.data)
          if (res.data.length === 0) {
            this.secondOraName.id = '机关总部'
            getUnitTree(Object.assign(this.secondOraName)).then(res => {
              this.unitTree = this.transformData(res.data)
            })
          }
        })
        // 获取违章类别树
        getVioTypeTree(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          this.vioTypeTree = this.formate(res.data)
        })
        // 获取隐患级别列表
        getHazardLevelList(Object.assign(this.queryParam)).then(res => {
          // console.log('隐患级别')
          this.dangerRiskData = res.data
          // console.log(this.dangerRiskData)
        })
        getDangerCheckType(Object.assign(this.queryParam)).then(res => {
          this.dangerCheckData = res.data
        })
        // 获取隐患类别树
        getDangerTree(Object.assign(this.queryParam)).then(res => {
          this.treeLoading = false
          this.dangerTypeTree = this.formate(res.data)
        })
        getDangerClause(Object.assign(this.queryParam)).then(res => {
          this.dangerClauseData = res.data
        })
      } catch (error) {
        console.error(error)
      }
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize)
    },
    mounted() {
      this.submitInfo.checkType = this.dataProp.check_Type
      this.submitInfo.checkTypeCode = this.dataProp.checkTypeCode
      // console.log(this.submitInfo.checkTypeCode)
      // console.log(this.submitInfo.checkType)
      window.addEventListener('resize', this.handleResize)
      this.handleResize()
      this.setDisabledToParent(this.unitTree)
      // 找出所有拥有子节点的节点并标记为“disabled”
      this.unitTree.forEach((node) => {
        if (node.children) {
          this.disabledIds.push(node.organizationId)
          node.children.forEach((child) => {
            this.disabledIds.push(child.organizationId)
          })
        }
      })
    },
    methods: {
      handleResize() {
        var myElement = this.$refs.myElement
        if (myElement) {
          var width = myElement.offsetWidth
          this.selectWidth = (width - 12 * 4) / 3 - 115
          this.selectWidth2 = width - (width - 12 * 4) / 3 - 115 - 12 * 2
        }
      },
      handleRadioChange(value) {
        if (value === '已整改') {
          this.isCheckDescriptionDisabled = false // 验收描述输入框可编辑
        } else if (value === '未整改') {
          this.isCheckDescriptionDisabled = true // 验收描述输入框禁用
        }
      },
      handleAlertClose() {
        this.isAlertVisible = false
      },
      setDisabledToParent(List) {
        // console.log('进入筛选')
        // console.log(List)
        List.forEach((item) => {
          item.disabled = true
          if (item.children && item.children.length > 0) {
            // 递归遍历子节点
            this.setDisabledToParent(item.children)
          }
        })
        // console.log(List)
      },
      handleModalCancel() {
        this.ModalVisible = false
      },
      getBase64(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = () => resolve(reader.result)
          reader.onerror = error => reject(error)
        })
      },
      handleCancel() {
        this.previewVisible = false
        this.visible = false
      },
      customRequest(option) {
      },
      async handleChange ({ fileList }) {
        this.fileList = fileList
        this.submitInfo.dangerFiles = []
        for (let i = 0; i < fileList.length; i++) {
          const file = fileList[i]
          const newFile = {
            name: file.name,
            base64Content: await this.getBase64(file.originFileObj)
          }
          this.submitInfo.dangerFiles.push(newFile)
        }
      },
      async handleChange2 ({ fileList2 }) {
        this.fileList2 = fileList2
        this.submitInfo.reformerFiles = []
        for (let i = 0; i < fileList2.length; i++) {
          const file2 = fileList2[i]
          const newFile2 = {
            name: file2.name,
            base64Content: await this.getBase64(file2.originFileObj)
          }
          this.submitInfo.reformerFiles.push(newFile2)
        }
      },
      formate(data) {
        return data.map(item => {
          item.value = item.id
          item.key = item.id
          if (item.children) {
            item.children = this.formate(item.children)
          }
          return item
        })
      },
      // 压缩并上传文件
      async dangerCompressAndUpload(file) {
        try {
          this.dangerShowLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.dangerShowLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      async reformerCompressAndUpload(file) {
        try {
          this.reformerShowLoader = true
          const image = await loadImageAsync(file) // 加载图片
          const canvas = document.createElement('canvas')
          const ctx = canvas.getContext('2d')
          // 调整图片尺寸
          const maxWidth = 800
          const maxHeight = 600
          let width = image.width
          let height = image.height
          if (width > maxWidth || height > maxHeight) {
            const ratio = Math.min(maxWidth / width, maxHeight / height)
            width *= ratio
            height *= ratio
          }
          // 根据目标文件大小调整压缩质量
          const maxSizeInBytes = 2 * 1024 * 1024 // 2MB
          let compressedFile = {}
          let quality = 0.9 // 初始压缩质量
          let compressedSize = Infinity
          // 迭代压缩直到文件大小符合要求
          while (compressedSize > maxSizeInBytes && quality > 0) {
            canvas.width = width
            canvas.height = height
            ctx.clearRect(0, 0, width, height)
            ctx.drawImage(image, 0, 0, width, height)
            // 将 canvas 转为 Blob 对象，并获取文件大小
            const blob = await new Promise((resolve) => {
              canvas.toBlob((blob) => {
                resolve(blob)
              }, file.type, quality)
            })
            compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            compressedSize = compressedFile.size
            // 降低压缩质量
            quality -= 0.1
          }
          const uid = 'vc-upload-' + compressedFile.lastModified + '-' + compressedFile.name.split('.')[0]
          compressedFile.uid = uid
          this.reformerShowLoader = false
          // console.log('compressedFile', compressedFile)
          return compressedFile // 解析 Promise 并将结果传递出去
        } catch (error) {
          throw error // 如果发生错误，则将错误传递出去
        }
      },
      async beforeUpload(file) {
        // console.log('这里是 beforeUpload')
        const type = this.$refs.DangerPics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            // console.log('file:', file)
              this.dangerCompressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                // resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          }
          let picTime = false
          return new Promise((resolve, reject) => {
            Exif.getData(file, function() {
              const exifData = Exif.getAllTags(this)
              let dateTimeOriginal = exifData.DateTimeOriginal
              const dateTime = exifData.DateTime
              if (!dateTimeOriginal && dateTime) {
                dateTimeOriginal = dateTime
              }
              if (exifData && dateTimeOriginal) {
                // console.log('dateTimeOriginal', dateTimeOriginal)
                picTime = true
              } else {
                picTime = false
              }
              resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
            })
          }).then(result => {
            resolve(file)
            // if (result) {
            //   // console.log('图片有拍摄时间')
            //   resolve(file)
            //   // 执行图片有拍摄时间时的操作
            // } else {
            //   this.$message.error('该图片没有拍摄时间')
            //   // console.log('图片没有拍摄时间')
            //   // 执行图片没有拍摄时间时的操作
            // }
          }).catch(error => {
            console.error(error)
          })
        })
      },
      async beforeUpload2(file) {
        // console.log('这里是 beforeUpload')
        const type = this.$refs.ReformerPics.$attrs['data-type']
        return new Promise((resolve, reject) => {
          // 校验文件类型
          const exName = file.name.split('.')[1]
          if (!type.includes(exName)) {
            this.$message.error('请检查文件类型,只允许上传图片文件')
            const error = new Error('请检查文件类型，只允许上传图片文件')
            reject(error)
          } else if (file.size / 1024 / 1024 > 2) {
            // console.log('file:', file)
              this.reformerCompressAndUpload(file)
              .then((compressedFile) => {
                // 处理 compressedFile
                // console.log('compressedFile:', compressedFile)
                file = compressedFile
                // resolve(file)
              })
              .catch((error) => {
                // 处理错误
                reject(error)
              })
              // const error = new Error('上传文件大小不能超过2MB')
              // reject(error)
          }
          let picTime = false
          return new Promise((resolve, reject) => {
            Exif.getData(file, function() {
              const exifData = Exif.getAllTags(this)
              let dateTimeOriginal = exifData.DateTimeOriginal
              const dateTime = exifData.DateTime
              if (!dateTimeOriginal && dateTime) {
                dateTimeOriginal = dateTime
              }
              if (exifData && dateTimeOriginal) {
                console.log('dateTimeOriginal', dateTimeOriginal)
                picTime = true
              } else {
                picTime = false
              }
              resolve(picTime) // 返回 picTime 的值到 Promise 的 resolve 函数
            })
          }).then(result => {
            resolve(file)
            // if (result) {
            //   // console.log('图片有拍摄时间')
            //   resolve(file)
            //   // 执行图片有拍摄时间时的操作
            // } else {
            //   this.$message.error('该图片没有拍摄时间')
            //   // console.log('图片没有拍摄时间')
            //   // 执行图片没有拍摄时间时的操作
            // }
          }).catch(error => {
            console.error(error)
          })
        })
      },
      // 关闭模态框（图片预览）
      handlePicCancel () {
        this.previewImage = ''
        this.previewVisible = false
      },
      handlePicCancel2 () {
        this.previewImage = ''
        this.previewVisible = false
      },
      // 打开模态框（图片预览）
      async handlePreview (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 打开模态框（图片预览）
      async handlePreview2 (file) {
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj)
        }
        this.previewImage = file.url || file.preview
        this.previewVisible = true
      },
      // 删除照片
      async handleRemove (file) {
        // if (this.fileList.length - 1 === 0) {
        //   this.batchExportLoading = false
        // }
        const index = this.fileList.indexOf(file)
        const newFileList = this.fileList.slice()
        newFileList.splice(index, 1)
        this.fileList = newFileList
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.fileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.submitInfo.dangerFiles = resultArray
      },
      async handleRemove2 (file) {
        // if (this.fileList2.length - 1 === 0) {
        //   this.batchExportLoading2 = false
        // }
        const index = this.fileList2.indexOf(file)
        const newFileList2 = this.fileList2.slice()
        newFileList2.splice(index, 1)
        this.fileList2 = newFileList2
        this.flag = false
        const outputArray = await convertFilesToArrayAsync(this.fileList)
        // 最终得到的 outputArray 数组包含多个输出对象
        // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
        const resultArray = outputArray.map(({ name, base64Content }) => ({
          name,
          base64Content
        }))
        // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
        this.submitInfo.reformerFiles = resultArray
      },
      // 上传图片方法
      async handlePicChange (file) {
        // console.log('开始了')
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件

        if (this.fileList.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          // console.log('开始了1')
          // this.batchExportLoading = true
          file.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file.file)
          this.fileList = file.fileList
          // 假设 this.fileList 是包含多个文件对象的数组
          const outputArray = await convertFilesToArrayAsync(this.fileList)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray = outputArray.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          // const last = resultArray[resultArray.length - 1]
          this.submitInfo.dangerFiles = resultArray
          // danComparePic(last).then(res => {
          //   console.log('开始了2')
          //   console.log(res.data)
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.fileList.pop()
          //     this.batchExportLoading = false
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     console.log('结束了')
          //   }
          // })
        } else {
          this.flag = true
        }
      },
      // 上传图片方法
      async handlePicChange2 (file2) {
        // 当删除的时候会触发onchange事件 因此使用flag控制onchange事件
        if (this.fileList2.length >= 4) {
          this.$message.warning('最多只能选择4张图片')
        }
        if (this.flag === true) {
          // this.batchExportLoading2 = true
          file2.file.status = 'done'
          const formData = new FormData()
          formData.append('file', file2.file)
          this.fileList2 = file2.fileList
          // 假设 this.fileList 是包含多个文件对象的数组
          const outputArray2 = await convertFilesToArrayAsync(this.fileList2)
          // 最终得到的 outputArray 数组包含多个输出对象
          // 将输出对象数组转换为仅包含 name 和 base64Content 两个属性的数组
          const resultArray2 = outputArray2.map(({ name, base64Content }) => ({
            name,
            base64Content
          }))
          // const last = resultArray2[resultArray2.length - 1]
          this.submitInfo.reformerFiles = resultArray2
          // danComparePic(last).then(res => {
          //   console.log('开始了')
          //   if (res.data) {
          //     this.$message.error('图片重复')
          //     this.fileList2.pop()
          //     this.batchExportLoading2 = false
          //   } else {
          //     // 最终得到的 resultArray 数组仅包含 name 和 base64Content 两个属性
          //     this.danComparePicFinished2 = true
          //     this.progressPercentage2 = 100
          //     this.batchExportLoading2 = false
          //     console.log('结束了')
          //   }
          // })
        } else {
          this.flag = true
        }
      },
      showModals() {
        this.visible = true
      },
      // 当选择作业专业时，影响关键作业类型和位置区域
      chooseWorkSpecialty(item) {
        this.submitInfo.workSpecialtyCode = item.specialtyCode
        // console.log(this.submitInfo.workSpecialtyCode)
        // 清空隐患类型，隐患级别，和隐患条款，隐患描述
        this.submitInfo.dangerTypeCategory = ''
        this.submitInfo.dangerType = ''
        this.chooseSpecialtyCode = item.specialtyCode
        this.searchSCode.Code = this.chooseSpecialtyCode
        this.searchSClauseCode.SpecialtyCode = this.chooseSpecialtyCode
        // 获取关键作业类型
        getKeyWorkTypeList(Object.assign(this.searchSCode)).then(res => {
          this.workTypeData = res.data.rows
          this.submitInfo.workType = ''
          // 重置位置区域
          this.submitInfo.location = ''
          // 重置关键作业内容
          this.submitInfo.workContent = ''
          // 重置风险作业等级
          this.submitInfo.workRisk = ''
        })
        // 获取位置区域
        getLocationList(Object.assign(this.searchSCode)).then(res => {
          this.locationData = res.data.rows
        })
        // 获取关键作业内容
        getKeyWorkContentList(Object.assign(this.searchWCode)).then(res => {
          this.workContentData = res.data.rows
          // console.log('关键作业内容：')
          // console.log(res.data.rows)
        })
      },
      choosedepart(item) {
        this.submitInfo.departmentCode = item.code
        // console.log(this.submitInfo.directDepartmentCode)
      },
      // 当选择隐患级别时，将隐患级别的specialtyCode保存到查询条件searchSClauseCode中，并进行查询
      chooseDangerType(item) {
        this.submitInfo.dangerTypeCode = item.code
        // console.log(this.submitInfo.dangerTypeCode)
        // 清空位置区域，隐患条款和隐患描述
        // this.dangerClauseData = []
        // this.submitInfo.dangerClause = ''
        // this.submitInfo.description = ''
        // this.submitInfo.location = ''
        // console.log('DangerTypeCode = ' + item.code)
        // this.searchSClauseCode.DangerTypeCode = item.code
        // this.searchGClauseCode.DangerTypeCode = item.code
      },
      // 当选择关键作业类型时，影响关键作业内容
      chooseWorkType(item) {
        this.chooseWorkTypeCode = item.workTypeCode
        this.searchWCode.Code = this.chooseWorkTypeCode
        this.submitInfo.keyWorkCode = item.workTypeCode
        // console.log(this.submitInfo.workTypeCode)
        getKeyWorkContentList(Object.assign(this.searchWCode)).then(res => {
          this.workContentData = res.data.rows
        })
      },
      // 当选择关键作业内容时，影响风险作业等级
      chooseWorkContent(item) {
        this.submitInfo.workRisk = item.workRisk
        // getGeneralDangerClause(12)
        // getSpecialtyDangerClause(12)
      },
      // 选择无条款时，为其他
      noClause() {
        this.submitInfo.dangerTypeCategory = '其他'
        this.submitInfo.description = '无对应条款'
        this.submitInfo.dangerType = ''
      },
      // 选择隐患条款时，隐患描述中显示相同的文字
      chooseDangerClause(item) {
        if (item === undefined) {
          this.submitInfo.description = ''
        }
        this.submitInfo.description = item.description
        this.searchCCode.id = item.generalSpecialtyId
        getDangerClauseAssocition(Object.assign(this.searchCCode)).then(res => {
          this.submitInfo.dangerTypeCategory = res.data.dangerTypeCategory
          this.submitInfo.dangerType = res.data.dangerType
          // this.submitInfo.dangerCategory = res.data.dangerCategory
          // this.hseData = res.data.hse
          // this.submitInfo.hseElement = this.hseData[0].item
        })
      },
      choosehse(item) {
        this.submitInfo.hseCode = item.code
        // console.log(this.submitInfo.hseElementCode)
      },
      handleDanCategoryClick(value, label, e) {
        if (e.triggerNode.$children.length === 0) {
          this.chooseDanCategoryId = e.triggerNode._props.value
          this.danQueryEleCom.Id = this.chooseDanCategoryId
          this.submitInfo.dangerCategory = e.triggerNode._props.title
          this.submitInfo.dangerCateId = e.triggerNode._props.value
          // console.log(this.submitInfo.dangerCategoryId)
          // 显示对应要素体系和对应安全沟通
          getDangerCategoryHse(Object.assign(this.danQueryEleCom)).then(res => {
            this.hseData = res.data.result
            // console.log(this.hseData)
            if (this.hseData.length) {
              if (this.submitInfo.dangerCategory !== '其它') {
                this.submitInfo.hseElement = this.hseData[0].item
                this.submitInfo.hseCode = this.hseData[0].code
                // console.log(this.submitInfo.dangerCategory)
              }
            } else {
              this.chooseDanCategoryId = ''
              this.submitInfo.dangerCategory = ''
              this.$message.warning('搜索隐患类别不正确.请重新搜索！')
            }
          })
        } else {
          this.chooseDanCategoryId = ''
          this.submitInfo.dangerCategory = ''
          this.$message.warning('非正确类别请重新选择！')
          // 提醒用户这不是叶子节点
        }
      },
      // 当单选改变时，设置隐患级别，位置区域，隐患条款，隐患描述为空
      changeRadio() {
        // this.submitInfo.description = ''
        // this.submitInfo.dangerType = ''
        // this.submitInfo.dangerClause = ''
        // this.submitInfo.location = ''
        // this.dangerClauseData = []
      },
      // 保存输入信息
      saveList() {
        console.log('this.danComparePicFinished', this.danComparePicFinished)
          if ([this.submitInfo.checkDate, this.submitInfo.organizationName, this.submitInfo.workItem, this.submitInfo.workSpecialty, this.submitInfo.dangerType,
          this.submitInfo.location, this.submitInfo.dangerClause, this.submitInfo.description, this.submitInfo.dangerTypeCategory, this.submitInfo.hseElement,
          this.submitInfo.causeAnalysis, this.submitInfo.directDepartment, this.submitInfo.reformerUserName, this.submitInfo.reformerDate, this.submitInfo.InspectionMethod].some(item => item === null || item === undefined)) {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.checkDate === '' || this.submitInfo.organizationName === '' || this.submitInfo.workItem === '' || this.submitInfo.workSpecialty === '' || this.submitInfo.dangerType === '' ||
          this.submitInfo.location === '' || this.submitInfo.dangerClause === '' || this.submitInfo.description === '' || this.submitInfo.dangerTypeCategory === '' || this.submitInfo.hseElement === '' ||
          this.submitInfo.causeAnalysis === '' || this.submitInfo.directDepartment === '' || this.submitInfo.reformerUserName === '' || this.submitInfo.reformerDate === '' || this.submitInfo.InspectionMethod === '') {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.description === '无对应条款') {
          this.$message.warning('隐患描述不允许为无对应条款')
        } else if (this.submitInfo.description === this.submitInfo.dangerClause) {
          this.$message.warning('隐患描述不允许和隐患条款相同')
        } else {
        //   if (!this.danComparePicFinished) {
        //   this.$message.warning('图片正在上传，请稍候再保存')
        // } else {
          this.saving = true
          if (this.addOrEdit === 0) {
            // const jobMajor = this.submitInfo.jobMajor
            addDangerInfo(this.submitInfo).then(response => {
              // console.log(this.submitInfo)
              // console.log(response.data)
              // 处理提交成功后的逻辑
              this.$message.success('保存隐患成功！')
              this.saved = true
              this.addOrEdit = 1
              // 获取qhseXyViolationId
              const qhseXyDangerId = response.data
              this.submitInfo.qhseXyDangerId = qhseXyDangerId
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                this.$message.error('保存隐患失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
          } else {
            // 实现编辑功能
            editDangerInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              this.$message.success('修改隐患成功！')
              this.addOrEdit = 1
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                this.$message.error('修改隐患失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving = false
              })
          }
        // }
        }
      },
      chooseReformerPeople(userName, userId) {
        this.submitInfo.reformerUserName = userName
        this.submitInfo.reformerUserId = userId
        // this.submitInfo.violationUserDepart = unitName
        this.visible = false
      },
      chooseanaly(item) {
        this.submitInfo.clauseAnalysisCode = item.code
        // console.log(this.submitInfo.causeAnalysisCode)
      },
      onSubmit2() {
        this.submitInfo.push = true
        console.log('this.submitifo', this.submitInfo)
        if ([this.submitInfo.checkDate, this.submitInfo.organizationName, this.submitInfo.workItem, this.submitInfo.workSpecialty, this.submitInfo.dangerType,
          this.submitInfo.location, this.submitInfo.dangerClause, this.submitInfo.description, this.submitInfo.dangerTypeCategory, this.submitInfo.hseElement,
          this.submitInfo.causeAnalysis, this.submitInfo.directDepartment, this.submitInfo.reformerUserName, this.submitInfo.reformerDate].some(item => item === null || item === undefined)) {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.checkDate === '' || this.submitInfo.organizationName === '' || this.submitInfo.workItem === '' || this.submitInfo.workSpecialty === '' || this.submitInfo.dangerType === '' ||
          this.submitInfo.location === '' || this.submitInfo.dangerClause === '' || this.submitInfo.description === '' || this.submitInfo.dangerTypeCategory === '' || this.submitInfo.hseElement === '' ||
          this.submitInfo.causeAnalysis === '' || this.submitInfo.directDepartment === '' || this.submitInfo.reformerUserName === '' || this.submitInfo.reformerDate === '') {
          this.$message.warning('信息尚未完善，请完善后再提交')
        } else if (this.submitInfo.description === '无对应条款') {
          this.$message.warning('隐患描述不允许为无对应条款')
        } else if (this.submitInfo.description === this.submitInfo.dangerClause) {
          this.$message.warning('隐患描述不允许和隐患条款相同')
        } else {
          this.saving1 = true
          if (this.addOrEdit === 0) {
            // const jobMajor = this.submitInfo.jobMajor
            addDangerInfo(this.submitInfo).then(response => {
              // console.log(this.submitInfo)
              // console.log(response.data)
              // 处理提交成功后的逻辑
              this.$message.success('保存隐患并推送成功！')
              this.saved = true
              this.addOrEdit = 1
              // 获取qhseXyViolationId
              const qhseXyDangerId = response.data
              this.submitInfo.qhseXyDangerId = qhseXyDangerId
              this.submitInfo.push = false
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                // 处理提交失败后的逻辑
                this.$message.error('保存隐患并推送失败！')
                this.submitInfo.push = false
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving1 = false
                this.submitInfo.push = false
              })
          } else {
            // 实现编辑功能
            editDangerInfo(this.submitInfo).then(response => {
              // 处理提交成功后的逻辑
              this.$message.success('修改隐患并推送成功！')
              this.addOrEdit = 1
            })
              // eslint-disable-next-line handle-callback-err
              .catch(error => {
                this.$message.error('修改隐患并推送失败！')
              })
              .finally(() => {
                // 不管成功失败都要取消loading状态
                this.saving1 = false
              })
          }
        }
      },
      onSubmit() {
        // console.log(this.submitInfo)
        // 处理提交成功后的逻辑
        this.fileList = []
        this.fileList2 = []
        this.addOrEdit = 0
        this.showCheck = false
        this.saved = false
        this.submitInfo = {
          ...this.submitInfo,
          qhseXyDangerId: '',
          checkType: this.dataProp.check_Type, // 检查类型
          checkTypeCode: this.dataProp.checkTypeCode,
          enterSys: '公司隐患违章系统',
          enterTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T'),
          dangerType: '', // 隐患级别
          description: '', // 隐患描述
          dangerCategory: '', // 隐患类别
          hseElement: '', // 对应要素体系
          observeComm: '', // 对应安全沟通
          causeAnalysis: '', // 原因分析
          directDepartment: '', // 归属部门
          potentialConsequence: '', // 可能后果
          dangerPic: '', // 隐患图片
          reformerUserId: '', // 整改负责人id
          reformerUserName: '', // 整改负责人姓名
          // reformerDate: '', // 整改期限
          reformerPic: '', // 整改图片
          // acceptanceDate: '', // 验收时间
          checkDescription: '', // 验收描述
          dangerTypeCategory: '', // 隐患性质分类
          dangerClause: undefined, // 隐患条款
          location: '' // 位置区域
        }
        this.enterTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
      },
      cancel() {
        this.$emit('cancel')
      },
      chooseDangerPeople(userName, userId) {
        this.submitInfo.reformerUserName = userName
        this.submitInfo.reformerUserId = userId
        this.visible = false
      },
      // 根据所选树的id获取title
      flattenData(data) {
        let result = []
        data.forEach(node => {
          result.push(node)
          if (node.children) {
            result = result.concat(this.flattenData(node.children))
          }
        })
        return result
      },
      // 寻找最深层结点
      deepList(data) {
        data.map((item) => {
          if (item.children && item.children.length > 0) {
            this.deepList(item.children)
          } else {
            // test数组存放
            this.test.push(item.id)
          }
        })
      },
      transformData(data) {
        function transform(data) {
          return data.map(item => ({
            id: item.id,
            label: item.title, // 将 title 转换为 label
            value: item.value,
            children: item.children ? transform(item.children) : []
          }))
        }
        return transform(data)
      },
      handleOrganNameClick(value, label, e) {
        if (value && label) {
          // 获取当前选择的单位的节点对象
          if (Array.isArray(label) && label.length > 0) {
            const selectedLabels = label.map(item => item.label)
            const selectedValues = value
            const lastSelectedLabel = selectedLabels[selectedLabels.length - 1]
            const lastSelectedValue = selectedValues[selectedValues.length - 1]
            this.submitInfo.organizationName = lastSelectedLabel // 将多个单位的标签用逗号分隔
            this.submitInfo.organizationId = lastSelectedValue // 将多个单位的值用逗号分隔
            // console.log(this.submitInfo.organizationName)
            // console.log(this.submitInfo.organizationId)
          } else {
            console.error('未选择单位或选择不正确')
          }
        }
      },
      moment,
      getCurrentData() {
        return new Date().toLocaleDateString()
      },
      // 日期选择器的change方法
      onChangeTime(dates, dateStrings) {
        // console.log(dates)
        // console.log(dateStrings)
        // const date = new Date(dateStrings)
        // const year = date.getFullYear() // 获取年份
        // const month = ('0' + (date.getMonth() + 1)).slice(-2) // 获取月份，需要补 0
        // const day = ('0' + date.getDate()).slice(-2) // 获取日期，需要补 0
        // this.submitInfo.checkDate = `${year}-${month}-${day}` // 将日期赋值为年-月-日格式
        // console.log('this.submitInfo.checkDate = ' + this.submitInfo.checkDate)
        const enterDate = moment(this.enterTime, 'YYYY-MM-DD HH:mm:ss')
        const differenceInSeconds = enterDate.diff(dates, 'seconds')
        const differenceInDays = enterDate.diff(dates, 'days')
        if (differenceInSeconds < 0) {
          this.$message.warning('检查时间不能晚于录入时间')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.submitInfo.checkDate = this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T')
        } else if (differenceInDays > this.$constants.timeInterval) {
          this.$message.warning('检查时间与录入时间不能超过' + this.$constants.timeInterval + '天')
          this.checkTime = enterDate.subtract(1, 'seconds')
          this.submitInfo.checkDate = this.checkTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T')
        } else {
          this.submitInfo.checkDate = dateStrings.replace(' ', 'T')
        }
      },
      onChangeTime2(dates, dateStrings) {
        const checkDate = moment(this.submitInfo.checkDate, 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = checkDate.diff(dates)
        if (differenceInDays > 0) {
          this.$message.warning('限期整改时间不能早于检查时间')
          this.reformTime = checkDate.add(1, 'seconds')
          this.submitInfo.reformerDate = this.reformTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T')
        } else {
          this.submitInfo.reformerDate = dateStrings.replace(' ', 'T')
        }
      },
      onChangeTime3(dates, dateStrings) {
        const checkDate = moment(this.submitInfo.checkDate, 'YYYY-MM-DD HH:mm:ss')
        const differenceInDays = checkDate.diff(dates)
        if (differenceInDays > 0) {
          this.$message.warning('验收时间不能早于检查时间')
          this.acceptTime = checkDate.add(1, 'seconds')
          this.submitInfo.acceptanceDate = this.acceptTime.format('YYYY-MM-DD HH:mm:ss').replace(' ', 'T')
        } else {
          this.submitInfo.acceptanceDate = dateStrings.replace(' ', 'T')
        }
      },
      handleOk() {
        this.$refs.table.refresh()
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      }
    }
  }
</script>
<style lang="less" scoped>
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
  .search-row {
    display: flex;
    align-items: center;
  }

  .search-buttons {
    display: flex;
    justify-content: flex-end;
  }
  .ant-form-item-label {
    width: 800px; /* 将标签宽度改为 100 像素 */
  }
  .item {
    margin: 20px; /* 根据需要调整上边距的值 */
  }
  .item2{
    margin-top: 60px;
  }
  .item3{
    margin-top: 20px;
  }
  .upload-item{
    margin-bottom: 20px;
  }
  .spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    animation: spin 2s linear infinite;
    margin: 20px auto;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
